import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)


const backgroundAudioManager = uni.getBackgroundAudioManager();

let lifeData = {};

try {
	// 尝试获取本地是否存在lifeData变量，第一次启动APP时是不存在的
	lifeData = uni.getStorageSync('lifeData');
} catch (e) {

}

// 需要永久存储，且下次APP启动需要取出的，在state中的变量名
let saveStateKeys = [
	'vuex_user',
	'vuex_token',
	'vuex_setting',
	'vuex_openid',
	'vuex_lasturl',
	'vuex_invitecode',
	'vuex_channel_id',
	'vuex_signin',
	'vuex_audio',
];

// 保存变量到本地存储中
const saveLifeData = function(key, value) {
	// 判断变量名是否在需要存储的数组中
	if (saveStateKeys.indexOf(key) != -1) {
		// 获取本地存储的lifeData对象，将变量添加到对象中
		let tmp = {};
		try {
			tmp = uni.getStorageSync('lifeData') || {};
		} catch (e) {
			console.error('获取缓存失败', e);
		}
		// 第一次打开APP，不存在lifeData变量，故放一个{}空对象
		tmp = tmp ? tmp : {};
		tmp[key] = value;
		// 执行这一步后，所有需要存储的变量，都挂载在本地的lifeData对象中
		try {
			uni.setStorageSync('lifeData', tmp);
		} catch (e) {
			console.error('保存缓存失败', e);
		}
	}
}

const store = new Vuex.Store({
	state: {
		// 如果上面从本地获取的lifeData对象下有对应的属性，就赋值给state中对应的变量
		// 加上vuex_前缀，是防止变量名冲突，也让人一目了然
		vuex_user: lifeData.vuex_user ? lifeData.vuex_user : {},
		vuex_token: lifeData.vuex_token ? lifeData.vuex_token : '',
		vuex_channel_id: lifeData.vuex_channel_id ? lifeData.vuex_channel_id : '',
		vuex_version: '1.0.1',
		vuex_config: {},
		vuex__token__: '',
		vuex_route: '',
		vuex_signin: lifeData.vuex_signin ? lifeData.vuex_signin : '', //签到init	
		vuex_invitecode: lifeData.vuex_invitecode ? lifeData.vuex_invitecode : '', //邀请码	
		vuex_openid: lifeData.vuex_user && lifeData.vuex_openid ? lifeData.vuex_openid : '',
		vuex_lasturl: lifeData.vuex_lasturl ? lifeData.vuex_lasturl : '/pages/index/index',
		vuex_audio: lifeData.vuex_audio ? lifeData.vuex_audio : {
			showGlobalPlayer: false,
			currentTrack: {
				title: '',
				author: '',
				coverImgUrl: '',
				src: '',
				currentTime: 0,
				duration: 0,
				isPlaying: false,
			},
			playType: 2, //1单曲循环2列表播放
			isPlaying: false,
			isSeeking: false,
			audioList: null,
			playlist: null,
			historyList: [],
			stopType: '',
			stopValue: 0,
			stopStatus: false,
			stopByTime: {
				timeShutDonw: null,
				stopTime: null,
			},
			stopByJishu: {
				playedNum: 0
			}
		},
		vuex_audio_status: {
			playType: 2, //1单曲循环2列表播放
			isPlaying: false,
			isSeeking: false,
		}

	},
	mutations: {
		SET_SHOW_GLOBAL_PLAYER(state, show) {
			state.vuex_audio.showGlobalPlayer = show;
			this.commit('SAVE_AUDIO_DATA');
		},
		SET_CURRENT_TRACK(state, track) {
			state.vuex_audio.currentTrack = track;
			this.commit('SAVE_AUDIO_DATA');
		},
		SET_IS_PLAYING(state, isPlaying) {
			state.vuex_audio_status.isPlaying = isPlaying;
			this.commit('SAVE_AUDIO_DATA_STATUS');
		},
		SET_RATE(state, rate) {
			state.vuex_audio.currentTrack.playbackRate = rate;
			this.commit('SAVE_AUDIO_DATA');
		},
		SAVE_AUDIO_DATA(state) {
			try {
				saveLifeData('vuex_audio', state.vuex_audio);
			} catch (error) {
				console.error('Failed to save audio data:', error);
			}
		},
		SAVE_AUDIO_DATA_STATUS(state) {
			try {
				saveLifeData('vuex_audio_status', state.vuex_audio_status);
			} catch (error) {
				console.error('Failed to save audio status data:', error);
			}
		},
		$uStore(state, payload) {
			// 判断是否多层级调用，state中为对象存在的情况，诸如user.info.score = 1
			let nameArr = payload.name.split('.');
			let saveKey = '';
			let len = nameArr.length;
			if (len >= 2) {
				let obj = state[nameArr[0]];
				for (let i = 1; i < len - 1; i++) {
					obj = obj[nameArr[i]];
				}
				obj[nameArr[len - 1]] = payload.value;
				saveKey = nameArr[0];
			} else {
				// 单层级变量，在state就是一个普通变量的情况
				state[payload.name] = payload.value;
				saveKey = payload.name;
			}
			// 保存变量到本地，见顶部函数定义
			saveLifeData(saveKey, state[saveKey])
		}
	},
	actions: {
		togglePlay({
			commit,
			dispatch,
			state
		}) { //播放点击
			const isPlaying = !state.vuex_audio_status.isPlaying;
			if (isPlaying) {
				if (!backgroundAudioManager.src) {
					dispatch('setCurrentTrack', state.vuex_audio.currentTrack)
				}
				backgroundAudioManager.play();
			} else {
				backgroundAudioManager.pause();
			}
		},

		setCurrentTrack({
			commit,
			dispatch,
			state
		}, track) { //设置音频参数
			if (state.vuex_audio.currentTrack && state.vuex_audio.currentTrack.id === track.id) {
				console.log('同一个音频')
			} else {
				console.log('不同音频')
				state.vuex_audio.currentTrack = track
			}
			backgroundAudioManager.title = track.title;
			backgroundAudioManager.singer = track.singer;
			backgroundAudioManager.coverImgUrl = track.coverImgUrl;
			backgroundAudioManager.src = track.src;
			backgroundAudioManager.startTime = track.currentTime;
			backgroundAudioManager.duration = track.duration;
			backgroundAudioManager.playbackRate = track.playbackRate || 1
			commit('SET_CURRENT_TRACK', track);
			commit('SET_SHOW_GLOBAL_PLAYER', true);
			backgroundAudioManager.onPlay(() => {
				uni.setNavigationBarTitle({
					title: state.vuex_audio.currentTrack.title
				});
				let part = state.vuex_audio.currentTrack.part
				let endTime = state.vuex_user.data.vip_expire_time * 1000
				let nowTime = new Date().getTime()
				if (part > 3 && endTime < nowTime) {
					backgroundAudioManager.pause()
					console.log('会员已到期')
					uni.showModal({
						title: '会员已到期',
						content: '您的会员已到期，当前音频只有VIP才能继续收听，确定去购买吗？',
						success(res) {
							if (res.confirm) {
								console.log('用户点击确定');
								uni.switchTab({
									url: '/pages/user/vip'
								})
							} else if (res.cancel) {
								console.log('用户点击取消');
								// uni.switchTab({
								// 	url: '/pages/index/index'
								// })
							}
						},
						fail() {}
					})
				}
				console.log('点击播放')
				commit('SET_IS_PLAYING', true);
				commit('SET_CURRENT_TRACK', state.vuex_audio.currentTrack);
			});
			backgroundAudioManager.onPause(() => {
				console.log('点击暂停')
				commit('SET_IS_PLAYING', false);
				dispatch('updateHistroyList', 0)
				dispatch('updatePlayList', 0)
			});
			backgroundAudioManager.onStop(() => {
				console.log('音频停止')
				commit('SET_IS_PLAYING', false);
				dispatch('updateHistroyList', 0)
				dispatch('updatePlayList', 0)
			})
			backgroundAudioManager.onTimeUpdate(() => {
				// 非手动调整进度中，更新显示的时间
				if (!state.vuex_audio_status.isSeeking) {
					state.vuex_audio.currentTrack.currentTime = backgroundAudioManager.currentTime
				}
				// state.vuex_audio.currentTrack.duration = backgroundAudioManager.duration
				//获取当前音频播放百分比
				// let percent = (backgroundAudioManager.currentTime / backgroundAudioManager.duration) * 100
				// state.vuex_audio.currentTrack.percent = percent
				commit('SET_CURRENT_TRACK', state.vuex_audio.currentTrack);
			});
			backgroundAudioManager.onEnded(() => {
				commit('SET_IS_PLAYING', false);
				console.log('播放结束');

				const {
					stopStatus,
					stopType,
					stopByJishu,
					stopValue
				} = state.vuex_audio;
				if (stopStatus && stopType === 'jishu') {
					if ((stopByJishu.playedNum + 1) < stopValue) {
						state.vuex_audio.stopByJishu.playedNum++;
					} else {
						state.vuex_audio.stopStatus = false;
						state.vuex_audio.stopByJishu.playedNum = 0;
						commit('SAVE_AUDIO_DATA', state.vuex_audio);
						return;
					}
					commit('SAVE_AUDIO_DATA', state.vuex_audio);
				}

				if (state.vuex_audio_status.playType === 1) {
					console.log('单曲循环');
					backgroundAudioManager.seek(0);
					backgroundAudioManager.play();
				} else {
					console.log('列表播放');
					dispatch('playNext');
				}
				dispatch('updateHistroyList', 1)
				dispatch('updatePlayList', 1)
				dispatch('refreshAudioList')
			});;
			backgroundAudioManager.onError((res) => {
				console.error('Background audio play error:', res);
				uni.showToast({
					title: '音频错误',
					icon: 'none'
				})
				commit('SET_IS_PLAYING', false);
			});
			backgroundAudioManager.onCanplay(() => {
				console.log('音频准备就绪')
			})
			backgroundAudioManager.play()
		},
		async playNext({
			commit,
			dispatch,
			state
		}) { // 播放下一首
			let currentIndex = state.vuex_audio.playlist.findIndex(item => item.mp3file_id === state
				.vuex_audio
				.currentTrack.mp3file_id);
			console.log('当前下标', currentIndex)
			if (currentIndex + 1 >= state.vuex_audio.playlist.length) {

				let currentIndex1 = state.vuex_audio.audioList.findIndex(item => item.id === state
					.vuex_audio.currentTrack.id)
				console.log('当前下标', currentIndex1, state.vuex_audio.currentTrack.mp3file_id, state
					.vuex_audio
					.audioList)
				if (currentIndex1 + 1 >= state.vuex_audio.audioList.length) {

					// 到达列表末尾，提示并暂停
					uni.showToast({
						title: '没有下一首了',
						icon: 'none'
					});
					backgroundAudioManager.pause();
				} else {
					let playAudio = state.vuex_audio.audioList[currentIndex1 + 1];
					let PostData = {
						ac: 'getdetail',
						id: playAudio.books_id
					};
					uni.$u.http.post('', PostData).then((res) => {
						let episodeList = res.list.map((item) => {
							return {
								books_id: item.books_id,
								id: playAudio.id,
								mp3file_id: item.id,
								title: item.title,
								author: res.data.author,
								album: item.album,
								singer: item.singer,
								coverImgUrl: res.data.cover_url,
								src: item.url,
								subtitles: [],
								isover: 0,
								part: item.part,
								currentTime: 0,
								duration: item.duration,
								playbackRate: 1, // 默认播放倍速
								audioProgress: 0 // 视频进度
							};
						});
						state.vuex_audio.playlist = episodeList;
						commit('SAVE_AUDIO_DATA', state.vuex_audio);
					});
					backgroundAudioManager.title = playAudio.title;
					backgroundAudioManager.singer = playAudio.author;
					backgroundAudioManager.coverImgUrl = playAudio.coverImgUrl;
					backgroundAudioManager.src = playAudio.src;
					commit('SET_CURRENT_TRACK', playAudio);
					return;
				}
			} else {
				let nextIndex = currentIndex + 1;
				let track = state.vuex_audio.playlist[nextIndex];
				backgroundAudioManager.title = track.title;
				backgroundAudioManager.singer = track.author;
				backgroundAudioManager.coverImgUrl = track.coverImgUrl;
				backgroundAudioManager.src = track.src;
				commit('SET_CURRENT_TRACK', track);
			}
			await dispatch('updateHistroyList', 1)
			await dispatch('updatePlayList', 1)
			await dispatch('refreshAudioList')
		},

		async playPrevious({
			commit,
			dispatch,
			state
		}) { // 播放上一首
			let currentIndex = state.vuex_audio.playlist.findIndex(item => item.mp3file_id === state
				.vuex_audio
				.currentTrack.mp3file_id);
			if (currentIndex === 0) {

				let currentIndex1 = state.vuex_audio.audioList.findIndex(item => item.id === state
					.vuex_audio.currentTrack.id)
				if (currentIndex1 === 0) {
					// 到达列表开头，提示并暂停
					uni.showToast({
						title: '没有上一首了',
						icon: 'none'
					});
					backgroundAudioManager.pause();
					return;
				} else {
					let playAudio = state.vuex_audio.audioList[currentIndex1 - 1];
					let PostData = {
						ac: 'getdetail',
						id: playAudio.books_id
					};
					uni.$u.http.post('', PostData).then((res) => {
						let episodeList = res.list.map((item) => {
							return {
								books_id: item.books_id,
								id: playAudio.id,
								mp3file_id: item.id,
								title: item.title,
								author: res.data.author,
								album: item.album,
								singer: item.singer,
								coverImgUrl: res.data.cover_url,
								src: item.url,
								subtitles: [],
								isover: 0,
								part: item.part,
								currentTime: 0,
								duration: item.duration,
								playbackRate: 1, // 默认播放倍速
								audioProgress: 0 // 视频进度
							};
						});
						state.vuex_audio.playlist = episodeList;
						commit('SAVE_AUDIO_DATA', state.vuex_audio);
					});
					backgroundAudioManager.title = playAudio.title;
					backgroundAudioManager.singer = playAudio.author;
					backgroundAudioManager.coverImgUrl = playAudio.coverImgUrl;
					backgroundAudioManager.src = playAudio.src;
					commit('SET_CURRENT_TRACK', playAudio);
					return;
				}
			} else {
				let prevIndex = currentIndex - 1;
				let track = state.vuex_audio.playlist[prevIndex];
				backgroundAudioManager.title = track.title;
				backgroundAudioManager.singer = track.author;
				backgroundAudioManager.coverImgUrl = track.coverImgUrl;
				backgroundAudioManager.src = track.src;
				commit('SET_CURRENT_TRACK', track);
			}
			await dispatch('updateHistroyList', 1)
			await dispatch('updatePlayList', 1)
			await dispatch('refreshAudioList')
		},

		setRate({
			commit,
			state
		}, rate) { // 设置播放速度
			console.log('设置播放速度', rate);

			// 设置播放速度
			backgroundAudioManager.playbackRate = rate;

			// 如果正在播放，重新播放以应用新的播放速度
			if (state.vuex_audio_status.isPlaying) {
				backgroundAudioManager.play();
			}

			// 更新 Vuex 状态
			commit('SET_RATE', rate);
		},
		setAudioTimer({
			commit,
			state
		}, minute) { // 按时间设置定时关闭
			if (minute == 0) {
				clearTimeout(state.vuex_audio.stopByTime.timeShutDonw)
				console.log('定时器已清除');
				return
			}
			const timeout = setTimeout(() => {
				backgroundAudioManager.stop(); // 停止播放
				console.log('音频已停止，定时器触发');
			}, minute * 60000); // 转换为毫秒
			//获取minute分钟后的时间

			state.vuex_audio.stopByTime = {
				stopTime: new Date().getTime() + minute * 60000,
				timeShutDonw: timeout
			}
			state.vuex_audio.stopStatus = true
			state.vuex_audio.stopType = 'time'
			state.vuex_audio.stopValue = minute
			commit('SAVE_AUDIO_DATA', state.vuex_audio)
		},
		clearAudioTimer({
			commit,
			state
		}) { //清除倒计时关闭定时器
			console.log('清除倒计时关闭定时器')
			clearTimeout(state.vuex_audio)
			state.vuex_audio.stopStatus = false
			state.vuex_audio.stopByJishu.playedNum = 0
			state.vuex_audio.stopByTime.timeShutDonw = null
			state.vuex_audio.stopByTime.stopTime = null
			commit('SAVE_AUDIO_DATA', state.vuex_audio)
		},
		seeked({
			commit,
			state
		}, currentTime) { //跳转到指定位置
			state.vuex_audio_status.isSeeking = false
			commit('SAVE_AUDIO_DATA_STATUS');
			backgroundAudioManager.seek(currentTime)
			backgroundAudioManager.play()
		},

		updatePlayList({
			commit,
			state
		}, isOver) { //更新播放列表
			let updata = {
				ac: 'updateplayposition',
				id: state.vuex_audio.currentTrack.id,
				play_position: state.vuex_audio.currentTrack.currentTime,
				isover: isOver
			}
			uni.$u.http.post('', updata).then(res => {
				console.log('更新播放列表')
			})
		},
		refreshAudioList({
			commit,
			state
		}) { //刷新待播列表
			let listData = {
				ac: 'getplaylist'
			};
			uni.$u.http.post('', listData).then(res => {
				let audioList = res.list.map((item) => ({
					books_id: item.books_id,
					id: item.id,
					mp3file_id: item.mp3file_id,
					title: item.title,
					author: item.author,
					album: item.album,
					singer: item.singer,
					coverImgUrl: item.cover_url,
					src: item.url,
					subtitles: [],
					isover: item.isover,
					part: item.part,
					currentTime: item.play_position,
					duration: item.duration,
					playbackRate: 1, // 默认播放倍速
					audioProgress: 0 // 视频进度
				}));
				state.vuex_audio.audioList = audioList
				commit('SAVE_AUDIO_DATA', state.vuex_audio)
			})
		},
		updateHistroyList({
			commit,
			state
		}, isFInished) { //更新播放历史
			let PostData = {
				ac: 'addhistory',
				books_id: state.vuex_audio.currentTrack.books_id,
				mp3file_id: state.vuex_audio.currentTrack.mp3file_id,
				part: state.vuex_audio.currentTrack.part,
				play_position: state.vuex_audio.currentTrack.currentTime,
				play_duration: state.vuex_audio.currentTrack.duration,
				is_finished: isFInished
			};
			uni.$u.http.post('', PostData).then((res) => {
				console.log('更新播放历史', res);
			});
		}
	}

})

export default store